//
//  RegisterViewController.m
//  leo
//
//  Created by 常艳 on 15/9/13.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "RegisterViewController.h"
#import "LeoMsg.h"
#import "SyncManager.h"
#import "FamilyViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
@interface RegisterViewController ()

@end

@implementation RegisterViewController
-(void)dealloc
{
    [self.timer invalidate];
    self.timer=NULL;
    self.syncer=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"注册账号";
    // Do any additional setup after loading the view from its nib.
    float x=self.phone.frame.size.height;
    UIView *phoneleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 76, x)];
    self.phone.leftView=phoneleftView;
    self.phone.leftViewMode=UITextFieldViewModeAlways;
    UIView *smsleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 76,x)];
    self.smsCode.leftView=smsleftView;
    UIView *nickleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 76,x)];
    self.smsCode.leftViewMode=UITextFieldViewModeAlways;
    self.nickName.leftView=nickleftView;
    self.nickName.leftViewMode=UITextFieldViewModeAlways;
    UIView *passleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 76,x)];
    self.pass.leftView=passleftView;
    self.pass.leftViewMode=UITextFieldViewModeAlways;
    self.timeLable.hidden=YES;
    self.isSendSms=NO;
    self.canSend=YES;
    self.syncer=[[SyncManager alloc] init];
    if(self.syncer==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 37"];
        return;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)register:(id)sender {
    [self.phone resignFirstResponder];
    [self.smsCode resignFirstResponder];
    [self.nickName resignFirstResponder];
    [self.pass resignFirstResponder];
    self.registerBtn.enabled=NO;
    self.canSend=NO;
    [self.indicator startAnimating];
    NSString *phone=[self.phone text];
    NSString *smsCode=[self.smsCode text];
    NSString *nickName=[self.nickName text];
    NSString *pass=[self.pass text];
    phone=[phone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    smsCode=[smsCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    nickName=[nickName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    pass=[pass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if(nickName==NULL||[nickName length]==0)
    {
        NSLog(@"%@,register,nickName is null ",Register_Tag);
        [self showErrorMsg:@"昵称不能为空"];
        self.canSend=YES;
        return;
    }
    if([Tooler checkStringIllegal:nickName ChnLength:6 EngLength:10]==1)
    {
        [self showErrorMsg:@"昵称不合法"];
        self.canSend=YES;
        return;
    }
    if([Tooler checkStringIllegal:nickName ChnLength:6 EngLength:10]==2)
    {
        [self showErrorMsg:@"昵称太长，中文字符只能输入6个，英文字符最多10个"];
        self.canSend=YES;
        return;
    }
    if(phone==NULL||[phone length]==0)
    {
        NSLog(@"%@,register,phone is null",Register_Tag);
        [self showErrorMsg:@"手机号不能为空"];
        self.canSend=YES;
        return;
    }
    if([phone length]!=11)
    {
        NSLog(@"%@,register,phone is illegal",Register_Tag);
        [self showErrorMsg:@"手机号码无效，请输入正确的手机号码"];
        self.canSend=YES;
        return;
    }
    if(![Tooler checkStringBegin:phone])
    {
        [self showErrorMsg:@"手机号码无效，请输入正确的手机号码"];
        self.canSend=YES;
        return;
    }
    if(smsCode==NULL||[smsCode length]==0)
    {
        NSLog(@"%@,register,smsCode is null.",Register_Tag);
        [self showErrorMsg:@"请输入验证码"];
        self.canSend=YES;
        return;
    }
    if(pass==NULL||[pass length]==0)
    {
        NSLog(@"%@,register,pass is null.",Register_Tag);
        [self showErrorMsg:@"密码不能为空"];
        self.canSend=YES;
        return;
    }
    if([pass length]<6)
    {
        NSLog(@"%@,register,pass is illegal.",Register_Tag);
        [self showErrorMsg:@"密码长度不能少于6个字符"];
        self.canSend=YES;
        return;
    }
    //发送验证码
    if(self.syncer==NULL)
    {
        NSLog(@"%@,register,syncer is null",Register_Tag);
        [self showErrorMsg:@"程序发生错误，code is 38"];
        self.canSend=YES;
        return;
    }
    [self.syncer verifySmsCode:phone smsCode:smsCode completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
        if(result==SUCESS)
        {
            //验证码正确，注册手机
            [self.syncer registerPhone:phone pass:pass nickname:nickName completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {

                if(result==SUCESS)
                {
                    //注册成功，后台登陆
                    [self.syncer loginPhone:phone pass:pass completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        [self.indicator stopAnimating];
                        DataManager *dataManager=[[DataManager alloc] init];
                        if(dataManager!=NULL)
                            [dataManager getActiveUser];
                        if(result==SUCESS)
                        {
                            AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                            if(mydelegate!=NULL)
                            {
                                /*
                                NSData *dataMsg=[mydelegate getLinkMsg:PT_SETUP_LINK];
                                if(dataMsg!=NULL)
                                {
                                    [mydelegate sendMsg:dataMsg];
                                }*/
                                mydelegate.islogin=YES;
                                [mydelegate connectToTcp];
                            }
                            //登陆成功，跳转完善账号信息
                            self.registerBtn.enabled=YES;
                            [self.timer invalidate];
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            FamilyViewController *familyViewController=[[FamilyViewController alloc] init];
                            UINavigationController *familyNav=[[UINavigationController alloc] initWithRootViewController:familyViewController];
                            if(mydelegate!=NULL)
                                [mydelegate setNavProperty:familyNav];
                            self.view.window.rootViewController=familyNav;
                            familyViewController=NULL;
                        }
                        else
                        {
                            //登陆失败，跳转登陆界面
                            [self showErrorMsg:@"注册成功，请登录"];
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            
                        }
                    }];

                }
                else
                {
                    [self.indicator stopAnimating];
                    if(result==NODATA)
                    {
                        [self showErrorMsg:@"当前网络异常，请检查网络"];
                    }
                    else
                    {
                        if(description!=NULL)
                        {
                            [self showErrorMsg:description];
                        }
                        else
                        {
                            [self showErrorMsg:@"注册失败"];
                        }
                    }
                    self.canSend=YES;
                }
            }];
            

        }
        else
        {
            [self.indicator stopAnimating];
            if(result==NODATA)
            {
                [self showErrorMsg:@"当前网络异常，请检查网络"];
            }
            else
            {
                if(description!=NULL)
                {
                    [self showErrorMsg:description];
                }
                else
                {
                    [self showErrorMsg:@"验证码验证失败"];
                }
            }
             self.canSend=YES;
        }
    }];
}
- (IBAction)getSmsCode:(id)sender {
    if(self.isSendSms==YES||self.canSend==NO)
        return;
    self.isSendSms=YES;
    [self.indicator startAnimating];
    NSString *phone=[self.phone text];
    if(phone==NULL)
    {
        NSLog(@"%@,getSmsCode,phone is null",Register_Tag);
        [self showErrorMsg:@"手机号码不能为空"];
        self.isSendSms=NO;
        return;
    }
    phone=[phone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([phone length]==0)
    {
        NSLog(@"%@,getSmsCode,phone is null",Register_Tag);
        [self showErrorMsg:@"手机号码无效，请输入正确的手机号码"];
        self.isSendSms=NO;
        return;
    }
    if([phone length]!=11||[Tooler checkStringBegin:phone]==NO)
    {
        NSLog(@"%@,getSmsCode,phone is null",Register_Tag);
        [self showErrorMsg:@"手机号码无效，请输入正确的手机号码"];
        self.isSendSms=NO;
        return;
    }
    if(self.syncer==NULL)
    {
        NSLog(@"%@,getSmsCode,syncer is null",Register_Tag);
        [self showErrorMsg:@"程序发生错误，code is 39"];
        self.isSendSms=NO;
        return;
    }
    [self.syncer getCheckCode:phone type:self.type completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        [self getSmsCallback:result retValue:retValue description:description];
    }];
}
-(void)getSmsCallback:(SyncResult) result retValue:(NSDictionary *)ret description:(NSString *)description
{
    [self.indicator stopAnimating];
    if(result==SUCESS)
    {
        NSLog(@"%@,getSmsCallback,success",Register_Tag);
        self.smsButton.backgroundColor=[UIColor grayColor];
        //进行倒计时
        self.seconds=60;
        NSString *timestr=[NSString stringWithFormat:@"%d           ",self.seconds];
        [self.smsButton setTitle:timestr forState:UIControlStateNormal];
        self.timeLable.hidden=NO;
        self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCutdown) userInfo:nil repeats:YES];
    }
    else
    {
        NSLog(@"%@,getSmsCallback,fail",Register_Tag);
        [Tooler showHttpMsg:result description:description msg:@"获取验证码失败"];
        self.isSendSms=NO;
        
    }
}
-(void)timeCutdown
{
    self.seconds--;
    if(self.seconds<=0&&self.timer!=NULL)
    {
        [self.timer invalidate];
        self.timeLable.hidden=YES;
        [self.smsButton setTitle:@"短信获取" forState:UIControlStateNormal];
        self.isSendSms=NO;
        self.smsButton.backgroundColor=[UIColor colorWithRed:57/255.0 green:157/255.0 blue:244/255.0 alpha:1.0];
    }
    else
    {
        NSString *timestr=[NSString stringWithFormat:@"%d           ",self.seconds];
        [self.smsButton setTitle:timestr forState:UIControlStateNormal];
    }

}

- (IBAction)backgroundTaped:(id)sender {
    [self.phone resignFirstResponder];
    [self.smsCode resignFirstResponder];
    [self.nickName resignFirstResponder];
    [self.pass resignFirstResponder];
}
-(void)showErrorMsg:(NSString *)msg
{
    self.registerBtn.enabled=YES;
    [self.indicator stopAnimating];
    [LeoMsg showMsg:msg];
}
- (IBAction)textFieldChange:(id)sender {
    if(self.phone.text.length>20)
        self.phone.text=[self.phone.text substringToIndex:20];
    self.phone.text=[Tooler validateNumber:self.phone.text];
    
}
- (IBAction)nickTextFieldChange:(id)sender {
    if(self.nickName.text.length>20)
        self.nickName.text=[self.nickName.text substringToIndex:20];
}
- (IBAction)passTextFieldChange:(id)sender {
    if(self.pass.text.length>20)
        self.pass.text=[self.pass.text substringToIndex:20];
}
- (IBAction)codeTextFieldChange:(id)sender {
    if(self.smsCode.text.length>6)
        self.smsCode.text=[self.smsCode.text substringToIndex:6];
    self.smsCode.text=[Tooler validateNumber:self.smsCode.text];
}

@end
